
Page({

  data: {
    avatarUrl:'',
    nickName:'',
    isLogin:false,
    isActive:4,
    openid:'',
    // 我报名的所有活动
    joinList:[],

    // 我发布的所有活动
    publishList:[],

    // 已删除（删除发布过的活动）
    deleteList:[],

    // 需要参加的活动
    needList:[],


    // 已取消的活动
    cancelList:[],

    // 被取消，也就是活动发布者删除了该活动
    byCancelledList:[],

    reminderPublishCount:0,
    reminderJoinCount:0
  },

  onLoad(){
    const userInfo = wx.getStorageSync('userInfo');
    if(userInfo){
      this.setData({
        avatarUrl:userInfo.avatarUrl,
        nickName:userInfo.nickName
      })
      this.getList()
    }
    if(wx.getStorageSync('isLogin')){
      this.setData({
        isLogin:true
      });
      this.reminderJoinPeople();
      this.reminderPublishPeople();
    }
  },

  onShow:function(){
    if(this.data.isLogin){

      this.getList();
    }
  },

  // 加载数据

  getList(){
    const that = this;
    wx.cloud.callFunction({
      name:'downMine',
      success:res=>{
        // console.log(res);
        const list = res.result.data;
        that.setData({
          joinList:list,
          cancelList:list.filter(item=>item.status===2),
          needList:list.filter(item=>item.status===1),
          byCancelledList:list.filter(item=>item.status === 4)
        });
      }
    });

    // 获取我发布的所有活动
    wx.cloud.callFunction({
      name:'downPublish',
      success:res=>{
        // console.log("downPublish",res);
        const list = res.result.data;
        that.setData({
          publishList:list,
          deleteList:list.filter(item=>item.status===2)
        })
      }
    })
  },

  // 点击进行登录
  login(e){
    // console.log("登录",e);
    const that = this;
    if(e.currentTarget.id === "true"){
      // 再次点击 提示是否退出登录
      wx.showModal({
        title: '提示',
        content: '是否退出登录',
        showCancel: true,
        cancelText: '取消',
        cancelColor: '#000000',
        confirmText: '确定',
        confirmColor: '#3CC51F',
        success: (result) => {
          if (result.confirm) {
            that.setData({
              avatarUrl:'',
              nickName:'',
              isLogin:false,
              // 我报名的所有活动
              joinList:[],
              // 已删除的活动
              deleteList:[],
              // 我发布的所有活动
              publishList:[],
              // 需要参加的活动
              needList:[],
              // 已取消的活动
              cancelList:[],
              // 被取消的活动
              byCancelledList:[],
            }) 
            wx.removeStorageSync('userInfo');
            wx.removeStorageSync('isLogin')
          }
        },
      });
        
    }else{
      wx.getUserProfile({
        desc:"获取用户头像和昵称并展示",
        success:(res)=>{
          console.log(res.userInfo);
          const userInfo = {
            avatarUrl:res.userInfo.avatarUrl,
            nickName:res.userInfo.nickName
          }
  
          // 将个人信息存储在本地中
          wx.setStorageSync('userInfo', userInfo);
  
          // 表示已经登录
          wx.setStorageSync('isLogin',true);
  
          that.setData({
            isLogin:true,
            avatarUrl:userInfo.avatarUrl,
            nickName:userInfo.nickName
          })

          that.getList();
          that.upUserInfo();
        }
      })
    }
  },

  // 切换显示

  handleListData(e){
    // console.log(e);

    this.setData({
      isActive: e.currentTarget.id
    });
  },


  // 跳转活动
  navToDetail(e){
    console.log(e);
    const id = e.currentTarget.id;
    wx.navigateTo({
      url: `/pages/detail/detail?id=${id}`,
    });
  },

  // 取消报名
  cancelActive(e){
    const id = e.currentTarget.id;
    console.log(id)
    // 待参加那一列 需要去掉
    // 已取消 则需要增加一个
    wx.cloud.callFunction({
      name:'cancelJoin',
      data:{
        id
      },
      success:res=>{
        console.log(res)
      }
    });

    let {joinList, cancelList,needList} = this.data;

    joinList.map(item=>{
      if(item._id === id){
        item.status = 2
      }
    })

    const index = needList.findIndex(item=>item.publish_id === id);

    const item = needList.splice(index,1);

    // console.log(index,item)
    cancelList.unshift(item[0]);
    this.setData({
      joinList,
      needList,
      cancelList
    })

  },



  // 跳转到报名者信息页面
  navtoCheckList(e){
    // console.log('跳转到查看报名者信息页面',e);

    const {id,peoplecount,title} = e.currentTarget.dataset;
    wx.navigateTo({
      url: `/pages/checkList/checkList?id=${id}&&peopleCount=${peoplecount}&&title=${title}`,
    });
      
  },

  // 删除已发布的活动 则需要将发布活动的状态改为2
  handleDeleteList(e){
    console.log('删除已发布',e);
    const id = e.currentTarget.dataset.id;
    let {publishList,deleteList,joinList,needList,byCancelledList} = this.data;
    const that = this;
    wx.showModal({
      title: '提示',
      content: '确定要删除已发布的活动？',
      showCancel: true,
      cancelText: '取消',
      cancelColor: '#000000',
      confirmText: '确定',
      confirmColor: '#3CC51F',
      success: (result) => {
        if (result.confirm) {
          // 确定要删除 找到id所在的记录，并将status改为2，表示该活动已被发布者删除了
          wx.cloud.callFunction({
            name:'updateStatus2',
            data:{
              id
            },
            success:res=>{
              console.log('状态更新成功')
            }
          });

          const index = publishList.findIndex(item=>item._id === id);

          publishList[index].status =2;

          deleteList.unshift(publishList[index]);

          that.setData({
            publishList,
            deleteList
          })


          // 如果我发起的活动，我也有报名的话，需要进行现有数据的修改
          const joinIndex =  joinList.findIndex(item=>item.publish_id === id);
          console.log('joinIndex',joinIndex)
          if(joinIndex>=0){
            joinList[joinIndex].status = 4;

            const needIndex = needList.findIndex(item=>item.publish_id === id);
            const item = needList.splice(needIndex,1);

            byCancelledList.unshift(item[0]);

            that.setData({
              joinList,
              needList,
              byCancelledList
            })
          }

        }
      },

    });
      
  },

  // 星号显示
  // 首页进行加载的时候，就需要判断有无活动需要进行提示
  async reminderJoinPeople(){
    let {result} = await wx.cloud.callFunction({
      name:'reminderJoin'
    })
    this.setData({
      reminderJoinCount:result.total
    })
  },

  async reminderPublishPeople(){
    let {result} = await wx.cloud.callFunction({
      name:'reminderPublish'
    })
    this.setData({
      reminderPublishCount:result.total
    })

  },


  // 登陆成功，将用户信息写入用户信息表
  upUserInfo(){
    const that = this;
    const {nickName,avatarUrl} = this.data;
    wx.cloud.callFunction({
      name:"upUserInfo",
      data:{
        nickName,
        avatarUrl
      },
      success:res=>{
        console.log("写入用户信息成功",res.result);
        if(res.result =='dark'){
          // 将登录状态置空，并提示被加入黑名单，无法信息登录
          wx.showModal({
            title: '提示',
            content: '由于被多人举报，您已被加入黑名单',
            showCancel: false,

            confirmText: '确定',
            confirmColor: '#3CC51F',
            success: (result) => {
              if (result.confirm) {
                if (result.confirm) {
                  that.setData({
                    avatarUrl:'',
                    nickName:'',
                    isLogin:false,
                    // 我报名的所有活动
                    joinList:[],
                    // 已删除的活动
                    deleteList:[],
                    // 我发布的所有活动
                    publishList:[],
                    // 需要参加的活动
                    needList:[],
                    // 已取消的活动
                    cancelList:[],
                    // 被取消的活动
                    byCancelledList:[],
                  }) 
                  wx.removeStorageSync('userInfo');
                  wx.removeStorageSync('isLogin')
                }
              }
            },

          });
          return;
            
        }else{
          this.setData({
            openid:res.result
          })
        }

      }
    })
  },

  // 切换到管理端
  toAdmin(){
    console.log("切换到管理端");
    wx.navigateTo({
      url: '/pages/admin/admin',
    });
      
  }
})